package jmind.core.log;

import java.io.File;
import java.io.FileNotFoundException;
import java.net.URL;

import jmind.base.util.reflect.ClassUtil;
import jmind.base.util.IpUtil;

import org.slf4j.LoggerFactory;
import org.slf4j.impl.StaticLoggerBinder;
import org.springframework.util.ResourceUtils;
import org.springframework.util.SystemPropertyUtils;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.net.SimpleSocketServer;
import ch.qos.logback.classic.selector.ContextSelector;
import ch.qos.logback.classic.util.ContextInitializer;
import ch.qos.logback.classic.util.ContextSelectorStaticBinder;
import ch.qos.logback.core.joran.spi.JoranException;

/**
 *   logback 集中管理
 <dependency>
 <groupId>uk.org.lidalia</groupId>
 <artifactId>sysout-over-slf4j</artifactId>
 <version>1.0.2</version>
 <optional>true</optional>
 </dependency>

 程序启动执行  SysOutOverSLF4J.sendSystemOutAndErrToSLF4J(); 就可以，不需要下面配置。 but  out 有bug 出不来，不知道为啥

  <!-- System.out.println & System.err.println handling through SLF4J -->
    <bean
        class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
        <property name="targetClass"
            value="uk.org.lidalia.sysoutslf4j.context.SysOutOverSLF4J" />
        <property name="staticMethod"
            value="uk.org.lidalia.sysoutslf4j.context.SysOutOverSLF4J.sendSystemOutAndErrToSLF4J" />
        <property name="arguments">
            <list>
                <!-- Set log level for System.out -->
                <util:constant static-field="uk.org.lidalia.sysoutslf4j.context.LogLevel.INFO" />
                <!-- Set log level for System.err -->
                <util:constant static-field="uk.org.lidalia.sysoutslf4j.context.LogLevel.ERROR" />
            </list>
        </property>
    </bean>
    
 * @link http://projects.lidalia.org.uk/sysout-over-slf4j/quickstart.html
 * 
 * @link  http://wenku.baidu.com/link?url=t8mKXviUk-lOMB_LikBO2UKRmQN5shEuGaeE_pAMLhRjKNqt8P3LABLrDcpW7HhrCXMzMKdaWUS0PCjJQ0xnlEMD7HiNHcrhOvdr8JoPvai&from_mod=download
 * @author xieweibo
 * @date 2015年6月30日
 */
public class LogbackConfigure {

    public static void main(String[] args) {
        if (args == null || args.length == 0) {
            args = new String[2];
            args[0] = "9527";
            args[1] = ClassUtil.getResourcePath("logback.xml");
            System.out.println("logback path=" + args[1]);
        }
        try {
            SimpleSocketServer.main(args);
        } catch (Exception e) {
            e.printStackTrace();
        }

        setLocalIp();

    }

    public static void setProperty(String name, String value) {
        LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
        lc.putProperty(name, value);
    }

    /**
     *设置本地ip到变量
     */
    public static void setLocalIp() {
        LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
        lc.putProperty("nodeIp", IpUtil.getLocalAddress());
    }

    public static void setLevel(String name, String level) {
        ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(name);
        logger.setLevel(Level.toLevel(level));

    }

    public static void setLevel(Class<?> clazz, Level level) {
        ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(clazz);
        logger.setLevel(level);

    }

    /**
     * Initialize logback from the given file.
     *
     * @param location the location of the config file: either a "classpath:" location
     *                 (e.g. "classpath:logback.xml"), an absolute file URL
     *                 (e.g. "file:C:/logback.xml), or a plain absolute path in the file system
     *                 (e.g. "C:/logback.xml")
     * @throws java.io.FileNotFoundException if the location specifies an invalid file path
     * @throws ch.qos.logback.core.joran.spi.JoranException
     *                                       Thrown
     */
    public static void initLogging(String location) throws FileNotFoundException, JoranException {
        String resolvedLocation = SystemPropertyUtils.resolvePlaceholders(location);
        URL url = ResourceUtils.getURL(resolvedLocation);
        LoggerContext loggerContext = (LoggerContext) StaticLoggerBinder.getSingleton().getLoggerFactory();

        // in the current version logback automatically configures at startup the context, so we have to reset it
        loggerContext.reset();

        // reinitialize the logger context.  calling this method allows configuration through groovy or xml
        new ContextInitializer(loggerContext).configureByResource(url);
    }

    /**
     * Set the specified system property to the current working directory.
     * <p/>
     * This can be used e.g. for test environments, for applications that leverage
     * LogbackWebConfigurer's "webAppRootKey" support in a web environment.
     *
     * @param key system property key to use, as expected in Logback configuration
     *            (for example: "demo.root", used as "${demo.root}/WEB-INF/demo.log")
     *  ch.qos.logback.ext.spring.web.WebLogbackConfigurer WebLogbackConfigurer
     */
    public static void setWorkingDirSystemProperty(String key) {
        System.setProperty(key, new File("").getAbsolutePath());
    }

    /**
     * Shut down Logback.
     * <p/>
     * This isn't strictly necessary, but recommended for shutting down
     * logback in a scenario where the host VM stays alive (for example, when
     * shutting down an application in a J2EE environment).
     */
    public static void shutdownLogging() {
        ContextSelector selector = ContextSelectorStaticBinder.getSingleton().getContextSelector();
        LoggerContext loggerContext = selector.getLoggerContext();
        String loggerContextName = loggerContext.getName();
        LoggerContext context = selector.detachLoggerContext(loggerContextName);
        context.reset();
    }

}
